<?php
namespace app\massage\model;

use app\BaseModel;
use app\shop\model\RefundOrder;
use think\facade\Db;

class CarAtvRecord extends BaseModel
{
    //定义表名
    protected $name = 'shequshop_car_atv_record';

    protected $append = [

        'content',

        'time_text',

        'game_info',

        'hx_user_name'

    ];


    /**
     * @author chenniang
     * @DataTime: 2021-09-28 14:12
     * @功能说明:核销人姓名
     */
    public function getHxUserNameAttr($value,$data){

        if(!empty($data['hx_user'])){

            $user_model = new User();

            $name = $user_model->where(['id'=>$data['hx_user']])->value('nickName');

            return $name;
        }

    }

    /**
     * @author chenniang
     * @DataTime: 2021-09-27 16:21
     * @功能说明:赛事信息
     */
    public function getGameInfoAttr($value,$data){

        if(!empty($data['id'])){

            $game_model = new CarGame();

            $dis = [

                'type' => 1,

                'record_id' => $data['id']
            ];

            $list = $game_model->dataInfo($dis);

            if(!empty($list)){

                $list['best_time']  = game_time($list['best_time']);

                $list['total_time'] = game_time($list['total_time']);

            }

            return $list;

        }

    }

    /**
     * @param $value
     * @param $data
     * @功能说明:转换时间
     * @author chenniang
     * @DataTime: 2021-09-26 1  4:11
     */
    public function getTimeTextAttr($value,$data){

        if(!empty($data['start_time'])&&!empty($data['end_time'])){

            $time = date('Y.m.d H:i',$data['start_time']).'-'.date('Y.m.d H:i',$data['end_time']);

            return $time;
        }



    }


    /**
     * @author chenniang
     * @DataTime: 2021-09-15 14:31
     * @功能说明:获取活动内容
     */
    public function getContentAttr($value,$data){

        if(!empty($data['id'])){

            $content = Db::name('shequshop_car_atv_record_content')->where(['record_id'=>$data['id']])->select()->toArray();

            return array_values($content);
        }

    }





    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:04
     * @功能说明:添加
     */
    public function dataAdd($data){

        $data['create_time'] = time();

        if(isset($data['content'])){

            $content = $data['content'];

            unset($data['content']);
        }

        $res = $this->insert($data);

        if(!empty($content)){

            $id = $this->getLastInsID();

            $this->updateSome($id,$content,$data['uniacid']);
        }

        return $res;

    }


    /**
     * @author chenniang
     * @DataTime: 2021-09-15 11:22
     * @功能说明:
     */
    public function updateSome($id,$content,$uniacid){

        Db::name('shequshop_car_atv_record_content')->where(['record_id'=>$id])->delete();

        if(!empty($content)){

            foreach ($content as $value){

                $insert = [

                    'uniacid' => $uniacid,

                    'content_id' => $value['content_id'],

                    'content_key' => $value['content_key'],

                    'content_value' => $value['content_value'],

                    'content_type' => $value['content_type'],

                    'record_id' => $id
                ];

                Db::name('shequshop_car_atv_record_content')->insert($insert);
            }

        }

        return true;

    }



    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:05
     * @功能说明:编辑
     */
    public function dataUpdate($dis,$data){

        if(isset($data['content'])){

            $content = $data['content'];

            unset($data['content']);
        }

        $res = $this->where($dis)->update($data);

        if(!empty($content)){

            $id = $this->getLastInsID();

            $this->updateSome($data['id'],$content,$data['uniacid']);
        }
        return $res;

    }


    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:06
     * @功能说明:列表
     */
    public function dataList($dis,$page=10,$mapor=[]){

        $data = $this->where($dis)->order('id desc')->paginate($page)->toArray();

        return $data;

    }


    /**
     * @author chenniang
     * @DataTime: 2021-09-16 13:57
     * @功能说明:成绩排行版
     */
    public function topRecordList($dis,$page=10,$mapor=[]){

        $data = $this->alias('a')
            ->join('massage_service_user_list b','a.user_id = b.id')
            ->where($dis)
            ->where(function ($query) use ($mapor){
                $query->whereOr($mapor);
            })
            ->field('a.*,b.nickName,b.avatarUrl')
            ->group('a.id')
            ->order('a.result asc,a.id desc')
            ->paginate($page)
            ->toArray();

        return $data;

    }


    /**
     * @author chenniang
     * @DataTime: 2021-09-16 13:57
     * @功能说明:成绩排行版(可根据时间)
     */
    public function timeTopRecordList($dis,$page=10,$time = 1,$mapor=[]){


        switch ($time){

            case 1:

                $time_text = 'day';

                break;
            case 2:

                $time_text = 'week';

                break;
            case 3:

                $time_text = 'month';

                break;
            case 4:

                $time_text = 'year';

                break;
        }

        $data = $this->alias('a')
            ->join('massage_service_user_list b','a.user_id = b.id')
            ->join('shequshop_car_game c','a.id = c.record_id')
            ->where($dis)
            ->whereTime('a.start_time',$time_text)
            ->where(function ($query) use ($mapor){
                $query->whereOr($mapor);
            })
            ->field('a.*,b.nickName')
            ->group('a.id')
            ->order('c.best_time asc,a.id desc')
            ->paginate($page)
            ->toArray();

        return $data;

    }


    /**
     * @author chenniang
     * @DataTime: 2021-09-16 13:57
     * @功能说明:积分排行榜
     */
    public function integralRecordList($dis,$page=10,$mapor=[]){

//        $data = $this->alias('a')
//            ->join('massage_service_user_list b','a.user_id = b.id')
//            ->where($dis)
//            ->where(function ($query) use ($mapor){
//                $query->whereOr($mapor);
//            })
//            ->field('a.*,b.nickName,b.avatarUrl')
//            ->group('a.id')
//            ->order('a.integral desc,a.id desc')
//            ->paginate($page)
//            ->toArray();


        $data = $this->alias('a')
            ->join('massage_service_user_list b','a.user_id = b.id')
            ->join('shequshop_car_game c','a.id = c.record_id','left')
            ->where($dis)
            ->where('a.pay_type','>',1)
            ->where(function ($query) use ($mapor){
                $query->whereOr($mapor);
            })
            ->field('a.*,c.best_time as best_time,b.nickName,b.avatarUrl')
            ->group('a.id')
            ->order(['a.integral desc','a.pay_type desc','c.best_time','a.id desc'])
            ->paginate($page)
            ->toArray();
        return $data;

    }

    /**
     * @author chenniang
     * @DataTime: 2021-09-16 13:57
     * @功能说明:记录列表
     */
    public function recordList($dis,$page=10,$mapor=[]){

        $data = $this->alias('a')
        ->join('massage_service_user_list b','a.user_id = b.id')
        ->where($dis)
        ->where(function ($query) use ($mapor){
            $query->whereOr($mapor);
        })
        ->field('a.*,b.nickName')
        ->group('a.id')
        ->order('a.id desc')
        ->paginate($page)
        ->toArray();

        return $data;

    }


    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:43
     * @功能说明:
     */
    public function dataInfo($dis){

        $data = $this->where($dis)->find();

        return !empty($data)?$data->toArray():[];

    }


    /**
     * @author chenniang
     * @DataTime: 2021-10-19 17:58
     * @功能说明:获取排名
     */
    public function getRecordTop($record){

        $dis = [

            'a.atv_id' => $record['atv_id']
        ];

        $data = $this->alias('a')
            ->join('shequshop_car_game c','a.id = c.record_id')
            ->where($dis)
            ->field('a.id')
            ->group('a.id')
            ->order(['a.integral desc','a.pay_type desc','c.best_time','a.id desc'])
            ->select()
            ->toArray();

        $top = 0;

        if(!empty($data)){

            foreach ($data as $k=>$v){

                if($v['id']==$record['id']){

                    $top = $k+1;
                }
            }
        }

        return $top;
    }


    /**
     * @author chenniang
     * @DataTime: 2021-09-16 13:57
     * @功能说明:记录列表
     */
    public function atvRecordList($dis,$page=10,$mapor=[],$rank = 2){

        $top = $rank==2?'a.integral':'a.integral desc';

        $data = $this->alias('a')
            ->join('shequshop_car_atv_list b','a.atv_id = b.id')
            ->join('shequshop_car_game c','a.id = c.record_id','left')
            ->where($dis)
            ->where(function ($query) use ($mapor){
                $query->whereOr($mapor);
            })
            ->field('a.*,b.title,b.cover,b.atv_num,b.atv_status,c.best_time as best_time,c.major')
            ->group('a.id')
            ->order([$top,'a.pay_type desc','c.best_time','a.id desc'])
            ->paginate($page)
            ->toArray();

        return $data;

    }


    /**
     * @author chenniang
     * @DataTime: 2021-09-26 16:44
     * @功能说明:支付回调
     */
    public function dataResult($order_code,$transaction_id){

        $data = $this->dataInfo(['order_code'=>$order_code]);

        if($data['pay_type']==1){
            //由于时效性问题 报名数量放到回调里面处理
//            $atv_model = new CarAtvList();
//
//            $atv = $atv_model->dataInfo(['id'=>$data['atv_id']]);
//            //报名已经满了
//            if($atv['atv_num']<=$atv['have_num']){
//
//                $this
//
//
//                //不再执行
//                return true;
//            }
//
//
//            $atv_model->where(['id'=>$data['atv_id']])->update(['have_num'=>Db::raw("have_num+1")]);

            $update = [

                'pay_type' => 2,

                'pay_time' => time(),

                'transaction_id' => $transaction_id
            ];

            $this->dataUpdate(['id'=>$data['id']],$update);
            //余额扣除
            if($data['balance']>0){

                $user_model = new User();

                $user = $user_model->dataInfo(['id'=>$data['user_id']]);

                $balance = $user['balance'] - $data['balance'];

                $user_model->dataUpdate(['id'=>$data['user_id']],['balance'=>$balance]);
            }

        }

        return true;

    }


    /**
     * @author chenniang
     * @DataTime: 2021-09-26 17:19
     * @功能说明:取消超时未支付的
     */
    public function autoCancelRecord($user_id=0){

        if(!empty($user_id)){

            $dis[] = ['user_id','=',$user_id];

        }else{

            $dis[] = ['over_time','<',time()];

        }

        $dis[] = ['pay_type','=',1];

        $list = $this->where($dis)->select()->toArray();

        if(!empty($list)){

            foreach ($list as $value){

                Db::startTrans();

                $res = $this->cancelRecord($value,1);

                if(!empty($res['code'])){

                    Db::rollback();
                }

                Db::commit();

            }

        }

        return true;

    }


    /**
     * @author chenniang
     * @DataTime: 2021-09-26 17:19
     * @功能说明:取消超时未支付的
     */
    public function cancelRecord($record,$auto_refund=0){

        $atv_model = new CarAtvList();

        $update = [

            'pay_type'    => -1,

            'refund_time' => time(),

            'auto_refund' => $auto_refund,

        ];

        $res = $this->dataUpdate(['id'=>$record['id']],$update);

        if($res==0){

            return ['code'=>500,'msg'=>'取消失败1'];
        }

        $atv = $atv_model->dataInfo(['id'=>$record['atv_id']]);

        $res = $atv_model->dataUpdate(['id'=>$record['atv_id']],['have_num'=>$atv['have_num']-1]);

        if($res==0){

            return ['code'=>500,'msg'=>'取消失败'];
        }

        return true;

    }


    /**
     * @author chenniang
     * @DataTime: 2021-11-12 15:06
     * @功能说明:积分到账
     */
    public function pointSuccess($uniacid){

        $dis = [

            'pay_type' => 7,

            'have_tx'  => 0,

            'uniacid'  => $uniacid

        ];

        $order = $this->where($dis)->field('id,integral,user_id,uniacid')->select()->toArray();

        if(!empty($order)){

            $integral_model = new \app\member\model\Integral();

            foreach ($order as $value){

                //修改订单状态
                $res = $this->where(['id'=>$value['id'],'have_tx'=>0])->update(['have_tx'=>1]);
                //增加用户积分
                if($res==1){

                    $integral_model->integralUserAdd($value['user_id'],$value['integral'],$value['uniacid'],2,8,$value['id']);

                }

            }

        }

        return true;

    }






}